package vendalenger.port;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.MalformedInputException;

import javax.swing.JOptionPane;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;

public class DownloadUtils {

	/**
	 * Download a file from the URL.
	 * 
	 * @exception IOException
	 *                when https:// Use http://
	 * @param http
	 *            The URL of the file to download.
	 * @param path
	 *            Destination of the file to download.
	 */
	public static void downloadFile(String http, String path) {
		URLConnection urlc;
		int i = 0;
		try {
			urlc = new URL(http).openConnection();
			File file = new File(path);
			BufferedInputStream bis = new BufferedInputStream(
					urlc.getInputStream());
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file.getName()));
			while ((i = bis.read()) != -1) {
				bos.write(i);
			}
			bos.close();
			bis.close();
		} catch (MalformedInputException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "Error downloading file. \n"
					+ e.getMessage(), "MalformedInputException",
					JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		} catch (IOException e1) {
			e1.printStackTrace();
			JOptionPane.showMessageDialog(null,
					"Error downloading file. \nCheck your internet connection: \n"
							+ e1.getMessage(), "IOException",
					JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
	}

	public static void unZip(String zip, String path) {
		try {
			ZipFile zipFile = new ZipFile(zip);
			zipFile.extractAll(path);
		} catch (ZipException e) {
			e.printStackTrace();
			JOptionPane
					.showMessageDialog(null, "Error extracting zip file: \n"
							+ e.getMessage(), "ZipException",
							JOptionPane.ERROR_MESSAGE);
		}
	}
}
